<?php

class RequestController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_request');
        $this->session_search_key = 'controller_request';
        $this->session_search_name = 'search_label';
        
        
        
        
        
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'request', '');
    }

    public function viewAction() {
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $req_id = $this->_getParam('req_id');
        } else {
            $this->_helper->redirector('list', 'request', '');
        }



        $requestModel = new Model_Request();
        $requestdata = $requestModel->fetchEntryByViewId($req_id, $this->USER->usr_lang_id);
        $updated_id = $requestdata['lgn_id'];
        /* get user name which is updated data* */
        $loginModel = new Model_Login();
        $updated_by_user = $loginModel->getUserData(Array('lgn_id' => $updated_id));
        $user_name = ucfirst($updated_by_user->name) . " [" . ucfirst($updated_by_user->role) . "]";

        $this->view->admindata = $user_name;
        $this->view->requestdata = $requestdata;
    }

    public function listAction() {
        $errorMessage = Array();
        $successmessage = "";
        $where = "1=1 ";
        $searchtype = "";
        $orderField = 'req_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }

        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }
        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }
        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = $this->ZFTRANSLATE->translate("select_one_checkbox");
                }
            }
            /* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where .= " and com_name LIKE '%$searchtype%' OR subj_name LIKE '%$searchtype%' OR site_name LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            }
        } else {
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            $where .= " and com_name LIKE '%$searchtype%' OR subj_name LIKE '%$searchtype%' OR site_name LIKE '%$searchtype%'";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
        }

        if ($this->USER->roletype == 'Customer' || $this->USER->roletype == 'SuperCustomer') {
            $where .= ' and com.com_id = ' . $this->USER->company_id;
        }

        $requestModel = new Model_Request();

        $requestsData = $requestModel->fetchRequest($where, $itemsPerPageReviews, $offset, $orderField, $sort);

        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($requestModel->getRequestCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'request', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->requestsData = $requestsData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $requestModel->getStatusArray($this->USER->usr_lang_id);
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load Request Model 
        $requestModel = new Model_Request();
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $request_id = $this->_getParam('req_id');
            $requestModel->deleteRequest($request_id);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("req_delete_success"));
            $this->_helper->redirector('list', 'request', '');
        } else {
            $requestModel->deleteRequest($ids);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("req_delete_success"));
            $this->_helper->redirector('list', 'request', '');
        }
    }

    public function formAction() {
        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $requestData = Array();
        $this->view->mode = "Add";
        $subj_where = '';
        $calloutData = "";

        //Load login Model
        $loginModel = new Model_Login();

        //load company model

        $companyModel = new Model_Company();

        //Load Request Model
        $requestModel = new Model_Request();

        //Load Request Form
        $requestForm = new Form_RequestForm();


        $imageName = "";

        //Load the customer array for the select box in form 
        /* $customerArray = $requestModel->getcustomerArray($this->USER->usr_lang_id);
          $requestForm->cust_id->addMultiOptions($customerArray);
         */
        $where = "com_type = 2 ";
        $companyArray = $requestModel->getcompanyArray($where);
        $requestForm->req_com_id->addMultiOptions($companyArray);

        //echo 'in';exit;
        //Load the site array for the select box in form 
        $siteArray = $requestModel->getsiteArray();
        $requestForm->site_id->addMultiOptions($siteArray);


        //Load the status array for the select box in form 
        $statusArray = $requestModel->getStatusArray($this->USER->usr_lang_id);
        $requestForm->req_status->addMultiOptions($statusArray);



        //Check for the request Parameter
        $requestData['req_id'] = $this->_request->getParam('req_id');
        $req_id = (!empty($requestData['req_id'])) ? $requestData['req_id'] : null;



        /* $calloutModel = new Model_Callout();
          $calloutData  = $calloutModel->fetchCallout("call.req_id = '".$req_id."'");
         */
        if (!empty($req_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $requestModel->fetchEntryById($req_id);
            $subj_where = "subject.site_id = '" . $data['site_id'] . "'";
            $this->view->view_subject_image = $data['subj_id'];
            $siteArray = $requestModel->getsiteArray("site.com_id = '" . $data['req_com_id'] . "'");
            $requestForm->site_id->addMultiOptions($siteArray);
        }

        //Load the subject array for the select box in form 
        $subjectArray = $requestModel->getsubjectArray($subj_where);
        $requestForm->subj_id->addMultiOptions($subjectArray);

        //Populate form 
        //$requestForm->req_date->setValue('date');
        $this->view->form = $requestForm->populate($data);





        if ($this->getRequest()->isPost()) {
            //Check for Errors

            if ($this->view->mode == "Add") {
                
            }

            $postedData = $this->_request->getPost();

            if ($postedData['req_com_id'] != '') {
                $siteArray = $requestModel->getsiteArray("site.com_id = '" . $postedData['req_com_id'] . "'");
                $requestForm->site_id->clearMultiOptions();
                $requestForm->site_id->addMultiOptions($siteArray);
            }


            if ($postedData['site_id'] != '') {
                $subjectArray1 = $requestModel->getsubjectArray("subject.site_id = '" . $postedData['site_id'] . "'");
                $requestForm->subj_id->addMultiOptions($subjectArray1);
            }

            if (!$requestForm->isValid($postedData)) {
                $errorMessage = $requestForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {

                if (count($errorMessageArray) > 0) {
                    
                } else {
                    if ($this->view->mode == "Add") {
                        $RequestCount = $requestModel->getRequestCount('');
                        $requestData['req_createddate'] = date("Y-m-d H:i:s");
                    }




                    /* authentication login id */
                    $updated_userid = $this->USER->lgn_id;
                    //Random number
                    $rand_ref = "req_" . rand(10000, 99999);
                    //Request save
                    $requestData['updated_lgn_id'] = $updated_userid;
                    $requestData['req_id'] = $req_id;
                    $requestData['site_id'] = $postedData['site_id'];
                    $requestData['subj_id'] = $postedData['subj_id'];
                    $requestData['req_com_id'] = $postedData['req_com_id'];
                    //$requestData['req_title'] = $postedData['req_title'];
                    $requestData['req_reference'] = $rand_ref;
                    $requestData['req_date'] = $postedData['req_date'];
                    $requestData['req_comment'] = $postedData['req_comment'];
                    $requestData['req_status'] = $postedData['req_status'];
                    $requestData['req_updateddate'] = date("Y-m-d H:i:s");
                    $requestModel->save($requestData, 'req_id');
                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("req_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("req_update_success");
                    }

                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'request', '');
                }
            }
        }
        //$this->view->calloutData = $calloutData;
        $this->view->mode = $this->view->mode;
        $this->view->requestid = $req_id;
        $this->view->imageName = $imageName;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $requestForm;
    }

    public function subjectlistAction() {
        $listString = "";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $requestModel = new Model_Request();

            $site_id = $postedData['site_id'];
            $subjectWhere = "subject.site_id = '" . $site_id . "'";
            //Load the customer array for the select box in form 
            $subjectArray = $requestModel->getsubjectArray($subjectWhere);
            $jsonString = "";
            foreach ($subjectArray as $key => $_subj) {
                $jsonString .= "<option value = '" . $key . "'>" . $_subj . "</option>";
            }
        }
        echo $jsonString;
        exit;
    }

    public function sitelistAction() {
        $listString = "";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $requestModel = new Model_Request();

            $req_com_id = $postedData['req_com_id'];
            $siteWhere = "site.com_id = '" . $req_com_id . "'";
            //Load the customer array for the select box in form 
            $siteArray = $requestModel->getsiteArray($siteWhere);
            $jsonString = "";
            foreach ($siteArray as $key => $_subj) {
                $jsonString .= "<option value = '" . $key . "'>" . $_subj . "</option>";
            }
        }
        echo $jsonString;
        exit;
    }

    public function subjectimageAction() {
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $subjectModel = new Model_Subject();
            $subj_id = $postedData['subj_id'];
            //$subjectWhere = "subject.subj_id = '" . $subj_id . "'";
            $subjectArray = $subjectModel->fetchEntryById($subj_id);
            if ($subjectArray['subj_instruction'] != '') {
                $src_path = $this->view->PUBLIC_PATH . "img/document.png";
                echo '<img src="' . $src_path . '"> &nbsp;&nbsp;
                <a class="label label-add" title="View" target="_blank" href="' . $this->view->url(array('controller' => 'request', 'action' => 'download', 'subj_id' => $subj_id), null, true) . '">
                  view </a>';
            }
        }
        exit;
    }

    public function calloutsubjectAction() {
        if ($this->getRequest()->isPost()) {
            $content = '';
            $postedData = $this->_request->getPost();
            $subjectModel = new Model_Subject();

            $subj_id = $postedData['subj_id'];
            //$subjectWhere = "subject.subj_id = '" . $subj_id . "'";

            $calloutModel = new Model_Callout();
            $calloutData = $calloutModel->fetchCallout("call.subj_id = '" . $subj_id . "'");


            if (count($calloutData) > 0) {
                $content = '<h3>' . $this->ZFTRANSLATE->translate("callout_subject") . '</h3><br/>
            <table class="table table-hover">
                    <thead>
                        <tr>
                            <th class="col-md-3 ">
                                ' . $this->ZFTRANSLATE->translate("call_frm_name") . '
                            </th>
                            <th class="col-md-3">
                                ' . $this->ZFTRANSLATE->translate("call_frm_phone") . '
                            </th>
                            <th class="col-md-3 ">
                                ' . $this->ZFTRANSLATE->translate("call_frm_comment") . '
                            </th>
                        </tr>
                    </thead>
                    <tbody>';
                $counter = 0;
                foreach ($calloutData as $key => $value) {
                    if ($counter == 0) {
                        $class = "class = first";
                    } else {
                        $class = "";
                    }
                    $content .= '<tr ' . $class . '>
                                    <td>
                                       ' . ucfirst($value['call_person']) . '
                                    </td>
                                    <td class="">
                                        ' . ucfirst($value['call_contact_no']) . '
                                    </td>
                                    <td class="">
                                        ' . $value['call_comment'] . '
                                    </td>
                                </tr>';
                    $counter++;
                }

                $content .= '</tbody></table>';
            }
            echo $content;
        }
        exit;
    }

    public function downloadAction() {
        $subjectModel = new Model_Subject();
        $subj_id = $this->_getParam('subj_id');
        $subjectArray = $subjectModel->fetchEntryById($subj_id);
        $document_name = $subjectArray['subj_instruction'];
        $file = $this->config->UPLOAD_PATH . "subject/" . $document_name;
        $gtlObj = new GTL_Common();
        $download_file = $gtlObj->dl_file($file);
    }

    public function commentAction() {
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $req_id = $this->_getParam('req_id');
        } else {
            if ($this->USER->role == 'ADMIN') {
                $this->_helper->redirector('dashboard', 'admin', '');
            } else if ($this->USER->role == 'CUSTOMER') {
                $this->_helper->redirector('dashboard', 'customer', '');
            } else {
                $this->_helper->redirector('dashboard', 'contractor', '');
            }
        }
        $requestData = array();
        $requestCommentData = array();
        $errorMessage = array();
        $successmessage = array();
        $requestModel = new Model_Request();
        $requestCommentModel = new Model_Requestcomment();
        // $req_id = $this->_request->getParam('req_id');
        $req_id = (!empty($req_id)) ? $req_id : null;
        $requestData = $requestModel->fetchEntryByViewId($req_id, $this->USER->usr_lang_id);

        $where = "req_id = " . $req_id;
        $requestCommentData = $requestCommentModel->fetchRequestComment($where);

        // request assign model
        $requestassignModel = new Model_Assignrequest();
        $requestassignData = $requestassignModel->fetchEntryByrequestId($req_id);


        //Request Log
        $requestlogModel = new Model_Requestlog();
        $where_log = "req_id = " . $req_id;
        $requestlogData = $requestlogModel->fetchRequestlog($where_log);




        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            if ($postedData['req_comment'] == '') {
                $errorMessage[] = "Please enter note";
            } else {



                //Image upload
                if ($_FILES['add_attachment']['name'] != '') {
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $folder = $this->config->UPLOAD_PATH . "comment_attachment/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);
                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $requestcommentData['cmnt_add_attachment'] = $fileName;
                        }
                    }
                }



                $requestcommentData['req_id'] = $req_id;
                $requestcommentData['cmnt_comment'] = $postedData['req_comment'];
                $requestcommentData['cmnt_createddate'] = date("Y-m-d H:i:s");
                $requestcommentData['cmnt_updateddate'] = date("Y-m-d H:i:s");
                $requestcommentData['cmnt_status'] = 1;


                if ($this->USER->role == 'ADMIN') {
                    $requestcommentData['adm_id'] = $this->USER->usr_id;
                    $requestcommentData['cmnt_comment_by'] = 1;
                }if ($this->USER->role == 'CONTRACTOR') {
                    $requestcommentData['cont_id'] = $this->USER->usr_id;
                    $requestcommentData['cmnt_comment_by'] = 2;
                }if ($this->USER->role == 'CUSTOMER') {
                    $requestcommentData['cust_id'] = $this->USER->usr_id;
                    $requestcommentData['cmnt_comment_by'] = 3;
                }
                $requestCommentModel->save($requestcommentData, 'cmnt_id');
                $successmessage = $this->ZFTRANSLATE->translate("comment_add_success");

                $this->addSuccessMessage($successmessage);
                $this->_helper->_redirector('comment', 'request', null, array('req_id' => $req_id));
                // $this->_helper->redirector('comment', 'request',  array('req_id' => $req_id));
            }
        }
        $this->view->requestlogData = $requestlogData;
        $this->view->requestassignData = $requestassignData;
        $this->view->succesMessage = $successmessage;
        $this->view->errorMessage = $errorMessage;
        $this->view->requestcommentData = $requestCommentData;
        $this->view->requestData = $requestData;
    }

    //LAyout for comment view popup
    public function commentedAction() {
        $this->_helper->layout()->setLayout('popup');
        if ($this->_getParam('req_id') && $this->_getParam('req_id') != "") {
            $req_id = $this->_getParam('req_id');
        } else {
            if ($this->USER->role == 'ADMIN') {
                $this->_helper->redirector('dashboard', 'admin', '');
            } else if ($this->USER->role == 'CUSTOMER') {
                $this->_helper->redirector('dashboard', 'customer', '');
            } else {
                $this->_helper->redirector('dashboard', 'contractor', '');
            }
        }
        $requestData = array();
        $requestCommentData = array();
        $errorMessage = array();
        $successmessage = array();
        $requestModel = new Model_Request();
        $requestCommentModel = new Model_Requestcomment();
        // $req_id = $this->_request->getParam('req_id');
        $req_id = (!empty($req_id)) ? $req_id : null;
        $requestData = $requestModel->fetchEntryByViewId($req_id, $this->USER->usr_lang_id);

        $where = "req_id = " . $req_id;
        $requestCommentData = $requestCommentModel->fetchRequestComment($where);

        // request assign model
        $requestassignModel = new Model_Assignrequest();
        $requestassignData = $requestassignModel->fetchEntryByrequestId($req_id);


        //Request Log
        $requestlogModel = new Model_Requestlog();
        $where_log = "req_id = " . $req_id;
        $requestlogData = $requestlogModel->fetchRequestlog($where_log);

        $this->view->requestlogData = $requestlogData;
        $this->view->requestassignData = $requestassignData;
        $this->view->succesMessage = $successmessage;
        $this->view->errorMessage = $errorMessage;
        $this->view->requestcommentData = $requestCommentData;
        $this->view->requestData = $requestData;
    }

}

?>
